package com.apes.fn.scm.retailOrder.model;

import com.apes.framework.jpa.BaseModel;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.util.ApesConst;
import com.apes.scm.masterdata.finance.model.BankAccount;
import com.apes.scm.masterdata.finance.model.PaymentMethodType;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 零售单付款方式
 *
 * @author wuq
 * @create 2020-03-18 9:05
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = RetailOrderPayMethod.CONST_TABLE_NAME)
public class RetailOrderPayMethod extends BaseModel {
    public static final String CONST_TABLE_NAME = "Retail_Order_Payment_Method";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "支付明细")
    @Comment("付款方式编码")
    private String id;

    @NotNull
    @ManyToOne(optional = false)
    @JoinColumn(name = "retail_order_id", referencedColumnName = "id")
    @Comment("付款单编码")
    private RetailOrder order; /*零售单主表*/

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="payment_method_type", referencedColumnName="id", nullable = false)
    @Comment("付款方式")
    private PaymentMethodType paymentMethodType;  //付款方式

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="customer_id", referencedColumnName="id")
    @Comment("付款客户")
    private PartyRole customer;  //客户

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="payment_Dept_id", referencedColumnName="id")
    @Comment("付款门店")
    private Dept paymentDept;   // 兑换券置换时传入

    @Column(name = "post_id", length = 120)
    @Comment("POS机编码")
    private String posId; //pos 机编码

    @Column(name = "bill_Number", length = 120)
    @Comment("票据号码")
    private String billNumber; //票据号码

    @Column(name = "amount", nullable = false, columnDefinition = ApesConst.FIELD_16_4)
    @Comment("付款金额")
    private double amount = 0; //付款金额

    @Column(name = "note", length = 250)
    @Comment("备注")
    private String note; //备注

    @Column(name = "account_number", length = 250)
    @Comment("银行账号")
    private String accountNumber; // 银行账号

    @Column(name = "advance_payment_id", length = 250)
    @Comment("订金单号")
    private String advancePaymentId; //订金单号

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="bank_account_id", referencedColumnName="id")
    @Comment("银行账户")
    private BankAccount bankAccount;  //银行账户

    /***
     * 类型为储值年卡订金消费
     */
    @Column(name = "platform_management_fee", nullable = false, columnDefinition = ApesConst.FIELD_16_4_0)
    @Comment("平台管理费")
    private double platformManagementFee = 0;
    /***
     * 渠道为天猫平台
     */
    @Column(name = "tmall_platform_fee", nullable = false, columnDefinition = ApesConst.FIELD_16_4_0)
    @Comment("三方平台引流成本")
    private double drainagePlatformFee = 0; // 原天猫平台费  改为三方平台引流成本

    /***
     * 渠道为车行易
     */
    @Column(name = "cxy_platform_fee", nullable = false, columnDefinition = ApesConst.FIELD_16_4_0)
    @Comment("车行易平台佣金")
    private double cxyPlatformFee = 0;

    @OneToMany(mappedBy = "retailOrderPayMethod", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<RetailPayMethodItem> retailPayMethodItems = new ArrayList<>();

    public List<RetailPayMethodItem> getRetailPayMethodItems(){
//        if (Objects.isNull(retailPayMethodItems))  throw new RuntimeException("没有收款方式明细，请检查");
        if (Objects.isNull(retailPayMethodItems))  retailPayMethodItems = new ArrayList<>();
        double itemAmounts = 0;
        for (RetailPayMethodItem item: retailPayMethodItems) {
            if (item.getAmount() == 0) throw new RuntimeException("收款方式明细存在为 0 的明细，请检查！");
            item.setRetailOrderPayMethod(this);

            if (Objects.nonNull(this.order)) item.setRetailOrderId(this.order.getId());

            itemAmounts += item.getAmount();
        }
        return retailPayMethodItems;
    }

    @Transient
    private PartyRole supplier;  // 供应商，供财务凭证取数使用

    protected PartyRole getSupplier() {
        if (Objects.isNull(this.customer)) return null;
        return this.customer.getParty().getPartyRoleByType("Supplier");
    }

    /**
     * 判断是否为其他应收
     * @return true 为其他应收， false 不为其他应收
     */
    public boolean checkIsOtherReceivables(){
        return Objects.equals("09", this.getPaymentMethodType().getId());
    }
}
